package com.business.wechat.handler;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import com.business.wechat.bean.WxUserBean;

import org.springframework.stereotype.Component;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import net.sf.rose.jdbc.dao.BeanDAO;
import net.sf.rose.jdbc.query.BeanSQL;
import net.sf.rose.jdbc.service.Service;
import net.sf.rose.util.StringUtil;

/**
 * 用户关注公众号Handler
 * <p>
 * Created by FirenzesEagle on 2016/7/27 0027. Email:liumingbo2008@gmail.com
 */
@Component
public class SubscribeHandler extends AbstractHandler {

	@Override
	public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
			WxSessionManager sessionManager) throws WxErrorException {
		WxMpUser mpUser = weixinService.getMpService().getUserService().userInfo(wxMessage.getFromUser(), "zh_CN");
		Service service = new Service();
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		try {
			String openId = mpUser.getOpenId();
			query.setEntityClass(WxUserBean.class);
			query.createSql("openId", openId);
			WxUserBean bean = dao.get();
			// 之前已经在平台关注过
			if (bean != null) {
				// 设置成关注
				WxUserBean wx = new WxUserBean();
				wx.setOpenId(openId);
				wx.setSubscribe(WxUserBean.SUBSCRIBED);
				wx.setSubscribeTime(new Date());
				// 特殊处理，如果是关注公众号，就把微信名称加入请求参数中，在WechatAction中借用这个属性的
				wx.setWeixinName(wxMessage.getCardId());
				query.createUpdateSql(wx);
				dao.update();
			} else {
				// 新增系统用户
				WxUserBean user = new WxUserBean();
				user.setOpenId(openId);
				user.setCity(mpUser.getCity());
				user.setCountry(mpUser.getCountry());
				user.setGroupId(mpUser.getGroupId());
				user.setHeadimgUrl(mpUser.getHeadImgUrl());
				user.setNickname(StringUtil.toBase64(mpUser.getNickname().getBytes()));
				if (mpUser.getPrivileges() != null) {
					user.setPrivileges(Arrays.toString(mpUser.getPrivileges()));
				}
				user.setProvince(mpUser.getProvince());
				user.setRemark(mpUser.getRemark());
				user.setSex(mpUser.getSex());
				// 1：已关注；2：取消关注
				user.setSubscribe(mpUser.getSubscribe() ? WxUserBean.SUBSCRIBED : WxUserBean.SUBSCRIBED_NO);
				user.setSubscribeTime(new Date());
				if (mpUser.getTagIds() != null) {
					user.setTagIds(Arrays.toString(mpUser.getTagIds()));
				}
				// 推荐人二维码code(采用时间戳的16进制)
				user.setQrcode(Long.toHexString(System.currentTimeMillis()));
				user.setUnionId(mpUser.getUnionId());
				query.createInsertSql(user);
				dao.update();
			}
			service.commit();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			service.close();
		}
		WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content("尊敬的" + mpUser.getNickname() + "您好，感谢您的关注！\n")
				.fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
		logger.info("subscribeMessageHandler" + m.getContent());
		return m;
	}
}
